import { _decorator, Component, Node, Animation, Collider2D, Contact2DType, CCString, IPhysics2DContact, Sprite } from 'cc';
import { Bullet } from './Bullet';
import { GameManager } from './GameManager';
const { ccclass, property } = _decorator;

@ccclass('Enemy')
export class Enemy extends Component {
    @property
    speed: number = 300;

    @property(Animation)
    anim: Animation;

    @property
    hp: number = 1;

    @property(CCString)
    animHit: string = "";
    @property(CCString)
    animDown: string = "";
    @property
    score: number = 100;


    collider: Collider2D = null;

    start() {
        this.collider = this.getComponent(Collider2D);
        if (this.collider) {
            this.collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
        }
        if (this.node.position.y < -580) {
            this.node.destroy();
        }
    }

    protected onDestroy(): void {
        if (this.collider) {
            this.collider.off(Contact2DType.BEGIN_CONTACT)
        }
    }

    update(dt: number) {
        //控制位移
        if (this.hp > 0) {
            const p = this.node.position;
            this.node.setPosition(p.x, p.y - this.speed * dt, p.z);
        }

        if (this.node.position.y < -500) {
            this.node.destroy();
        }

    }

    onBeginContact(selfColloder: Collider2D, otherColloder: Collider2D, contact: IPhysics2DContact | null) {
        //通过播放动画对Enemy进行一个(隐身)
        this.hp -= 1;
        if (otherColloder.getComponent(Bullet)) {
            otherColloder.enabled = false;
            otherColloder.getComponent(Sprite).enabled = false;
        }

        if (this.hp > 0) {
            this.anim.play(this.animHit)
        } else {
            this.anim.play(this.animDown);
        }


        if (this.hp <= 0) {
            GameManager.getInstance().addScore(this.score);
            if (this.collider) {
                this.collider.enabled = false;
            }
            this.scheduleOnce(() => {
                this.node.destroy();
            }, 1)
        }
    }
}


